package net.lulihu.pangolin.headless.server.kit;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import net.lulihu.pangolin.headless.common.util.ChannelTwoWayBindKit;
import net.lulihu.pangolin.headless.common.util.IDGeneratorKit;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 服务器等待绑定通道工具
 */
@Slf4j
public class ServerWaitBindChannelKit {

    // 等待绑定的用户通道 k-> 唯一id，value,用户通道
    private static final Map<String, Channel> waitUserChannelMapper = new ConcurrentHashMap<>();

    /**
     * 放置等待绑定的通道
     *
     * @param channel1 通道1
     * @return 唯一id
     */
    public static String putWaitBindChannel(Channel channel1) {
        String channelId = IDGeneratorKit.getStr();
        waitUserChannelMapper.put(channelId, channel1);
        return channelId;
    }

    /**
     * 取出等待绑定的通道
     *
     * @param channelId 通道id
     * @return 通道
     */
    public static Channel takeWaitBindChannel(String channelId) {
        return waitUserChannelMapper.remove(channelId);
    }


    /**
     * 使用指定id获取等待绑定的通道与服务器通道进行双向绑定
     *
     * @param id       唯一id
     * @param channel2 通道2
     * @return true绑定成功 反正id不存在绑定失败
     */
    public static Channel bindChannelAndReturn(String id, Channel channel2) {
        Channel channel1 = takeWaitBindChannel(id);
        if (channel1 != null) {
            ChannelTwoWayBindKit.twoWayBindingChannel(channel1, channel2);
        }
        return channel1;
    }

}
